// miniprogram/pages/detail/detail.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _id: null,
    publisher: null,
    detail: [],
    isShowModal: false,
    reason: "",
    remove: false
  },

  /**
   * 复制联系方式
   */
  copyText: function (t) {
    wx.setClipboardData({
      data: t.currentTarget.dataset.text,
      success: function (t) {
        wx.getClipboardData({
          success: function (t) {
            wx.showToast({
              title: "已复制到粘贴板"
            });
          }
        });
      }
    });
  },

  /**
   * 显示图片
   */
  showPic(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.detail.imgs[index],
      urls: this.data.detail.imgs,
    })
  },

  /**
   * 确认认领或拾到
   */
  confirmFinish() {
    let _this = this;
    let id = this.data._id;
    let userid = this.data.userinfo._openid
    let tip = this.data.detail.type === 'lost' ? '拾到' : '认领'

    wx.showModal({
      title: '提示',
      content: '确认' + tip,
      success(res) {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: "detail",
            data: {
              $url: 'confirmFinish',
              id
            }
          }).then(res => {
            if (res.result.code === 200) {
              _this.setData({
                'detail.status': 'finish',
                'detail.other': userid
              })
              wx.showToast({
                title: '操作成功',
              })
            } else {
              wx.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          })

        } else if (res.cancel) {
          console.log('用户取消' + tip)
        }
      }
    })
  },

  /**
   * 取消认领或拾到
   */
  cancelFinish() {
    let _this = this;
    let id = this.data._id;
    let tip = this.data.detail.type === 'lost' ? '拾到' : '认领'

    wx.showModal({
      title: '提示',
      content: '确认取消' + tip,
      success(res) {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: "detail",
            data: {
              $url: 'cancelFinish',
              id
            }
          }).then(res => {
            if (res.result.code === 200) {
              _this.setData({
                'detail.status': 'progress'
              })
              wx.showToast({
                title: '操作成功',
              })
            } else {
              wx.showToast({
                title: '操作失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  /**
   * 显示提示框
   */
  doRemoveByRole() {
    let _this = this
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    wx.cloud.callFunction({
      name: 'verify',
      data: {
        $url: 'verifyAdmin'
      }
    }).then(res => {
      if (res.result.result) {
        this.setData({
          isShowModal: true
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '确认删除',
          success(res) {
            if (res.confirm) {
              _this.remove()
            } else if (res.cancel) {
              console.log('用户取消删除')
            }
          }
        })
      }
      wx.hideLoading()

    })

  },

  /**
   * 删除
   */
  remove() {
    let _this = this;
    let id = this.data._id;
    let openid = this.data.detail._openid;

    wx.cloud.callFunction({
      name: "list",
      data: {
        $url: 'removeItem',
        openid,
        id
      }
    }).then(res => {
      if (res.result.code === 200) {
        wx.showToast({
          title: '删除成功',
          duration: 2000,
          mask: true,
          success: function () {
            setTimeout(function () {
              _this.reloadPrevData()
              wx.navigateBack()
            }, 2000);
          }
        })
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        })
      }
    })

  },

  setValue(e) {
    this.setData({
      reason: e.detail.value
    })
  },

  async confirm() {
    if (!this.data.reason) {
      wx.showToast({
        title: '不能为空',
        icon: 'none'
      })
      return
    }
    const r = await wx.cloud.callFunction({
      name: 'message',
      data: {
        $url: 'sendMessage',
        content: "你发布的信息已被管理员删除，原因：" + this.data.reason,
        to: this.data.publisher._openid,
        listid: this.data._id
      }
    })
    if (r.result.code === 200) {
      this.remove()
    }
    this.cancel()
  },

  cancel() {
    this.setData({
      isShowModal: false
    })
  },

  /**
   * 加载用户信息
   */
  _loadUserinfo() {
    wx.cloud.callFunction({
      name: "user",
      data: {
        $url: 'getUserinfo'
      }
    }).then(res => {
      if (res.result.code === 200) {
        this.setData({
          userinfo: res.result.data[0]
        })
      } else {
        wx.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 加载发布者信息
   */
  _loadPubliserInfo(_openid) {
    let _this = this
    wx.cloud.callFunction({
      name: "detail",
      data: {
        $url: 'getPublisher',
        _openid
      }
    }).then(res => {
      if (res.result.code === 200) {
        _this.setData({
          publisher: res.result.data
        })
      }
    })
  },

  /**
   * 加载细节数据
   */
  async _loadData(_id) {
    wx.showLoading({
      title: '请稍等',
      mask: true
    })
    if (!_id) {
      _id = this.data._id
    }
    const db = wx.cloud.database()
    let res = null
    try {
      res = await db.collection('list').doc(_id).get()
    } catch (err) {
      console.log(err)
      wx.hideLoading()
      wx.showToast({
        title: '查看详情失败',
        icon: 'none'
      })
      wx.navigateBack()
    }
    console.log(res);
    wx.hideLoading()
    if (res) {
      res.data.date = (new Date(res.data.date)).getTime()
      res.data.publishDate = (new Date(res.data.publishDate)).getTime()
      this._loadPubliserInfo(res.data._openid)
      this.setData({
        detail: res.data,
      })
    }

  },

  /**
   * 返回上一个页面
   */
  reloadPrevData() {
    const pages = getCurrentPages(); //获取页面栈
    const prevPage = pages[pages.length - 2]; //前一个页面
    let tmpData = prevPage.data.result;
    tmpData[this.data._index] = this.data.detail;
    prevPage.setData({
      result: tmpData
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const _id = options.id.trim()
    const _index = options.index.trim()
    const remove = options.delete

    console.log(_id);
    this.setData({
      _id,
      _index,
      remove: remove == 'true' ? true : false
    })
    this._loadData(_id)
    this._loadUserinfo()
  },

  /**
   * 生命周期函数--页面卸载
   */
  onUnload: function (){
    this.reloadPrevData()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})